package logic

import (
	"blog/models/cache"
	"blog/models/mysql"
	"blog/pkg"
	"blog/userrpc/internal/svc"
	"blog/userrpc/userrpc"
	"context"
	"fmt"

	"github.com/zeromicro/go-zero/core/logx"
)

type RegisterLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewRegisterLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RegisterLogic {
	return &RegisterLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *RegisterLogic) Register(in *userrpc.RegisterRequest) (*userrpc.RegisterResponse, error) {
	// todo: add your logic here and delete this line
	var mo mysql.User
	mysql.DB.Debug().Where("mobile = ?", in.Mobile).Find(&mo)
	if mo.ID != 0 {
		return nil, fmt.Errorf("手机号已存在,无法注册")
	}

	var us mysql.User
	mysql.DB.Debug().Where("username = ?", in.Username).Find(&us)
	if us.ID != 0 {
		return nil, fmt.Errorf("账号已存在,无法注册")
	}

	se := cache.Rdb.Get(cache.Ctx, "snedSms"+in.Mobile)
	if se.Val() != in.SendSmsCode {
		return nil, fmt.Errorf("手机验证码错误")
	}

	ca := cache.Rdb.Get(cache.Ctx, "captcha"+in.Username)
	if ca.Val() != in.CaptchaCode {
		return nil, fmt.Errorf("图形验证码错误")
	}
	var user = mysql.User{
		Username: in.Username,
		Password: pkg.MD5(in.Password),
		Mobile:   in.Mobile,
	}
	mysql.DB.Debug().Create(&user)
	return &userrpc.RegisterResponse{
		Id: int64(user.ID),
	}, nil
}
